﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using NCP.Infrastructure.Common.Domain;
using NCP.Recruiting.ApplicationServices.Interfaces;
using NCP.Recruiting.ApplicationServices.Messaging.Companies;
using NCP.Recruiting.ApplicationServices.Messaging.Jobpositions;
using NCP.Recruiting.ApplicationServices.Shared;
using NCP.Recruiting.ApplicationServices.ViewModels;
using NCP.Recruiting.Web.Framework.Controllers;
using NCP.Recruiting.WebApp.Models;
using NCP.Recruiting.ApplicationServices.Messaging.Settings;
using NCP.Recruiting.WebApp.Extensions;


namespace NCP.Recruiting.WebApp.Controllers
{
    public class JobPositionController : AuthorizedController
    {

        #region Const
        private readonly ICompanyAppService _CompanyAppService;
        private readonly IJobPositionAppService _JobPositionAppService;
        private readonly ISettingAppService _DepartmentAppService;
        private const int _pageSize = 15;
        private const String _dateFormat = "yyyy/MM/dd";
        private const String _dateFormatTime = "yyyy/MM/dd HH:mm:ss";
        private const String _defaultKeyword = "关键字过滤";
        #endregion


        public JobPositionController(ICompanyAppService companyAppService, IJobPositionAppService jobpositionAppService, ISettingAppService departmentAppService)
            : base(companyAppService)
        {
            this._JobPositionAppService = jobpositionAppService;
            this._CompanyAppService = companyAppService;
            this._DepartmentAppService = departmentAppService;
        }

        public ActionResult Index()
        {
            return View();
        }

        #region List

        public ActionResult List(PagingFilteringModel command,
            JobQueryStatus jobQueryStatus = JobQueryStatus.All,
            String keyword = "")
        {
            if (command == null)
            {
                command = TempData["command"] as PagingFilteringModel;
                jobQueryStatus = (JobQueryStatus)TempData["jobQueryStatus"];
                keyword = TempData["keyword"] as String;
            }

            //初始化分页组件
            if (command.PageSize <= 0)
                command.PageSize = _pageSize;
            if (command.PageNumber <= 0)
                command.PageNumber = 1;
            //如果关键字等于默认关键字则置空
            if (keyword.Equals(_defaultKeyword))
                keyword = String.Empty;
            //取得分页数据
            var request = new SearchListRequest() { CompanyId = this.CurrentUserId, JobPositionStatus = jobQueryStatus, Keyword = keyword, PageIndex = command.PageIndex, PageSize = command.PageSize };
            var response = _JobPositionAppService.SearchList(request);
            var model = new JobPositionListViewModel()
            {
                PagingFilteringContext = new PagingFilteringModel(),
            };
            model.PagingFilteringContext.LoadPagedList(response.ListItemModelList);
            //转换成ViewModel
            model.JobPositionList = response.ListItemModelList;
            model.Keyword = keyword;
            model.JobQueryStatus = jobQueryStatus;
            //获取公司信息
            var responseGetInfoById = _CompanyAppService.GetInfoById(new GetInfoByIdRequest() { Id = this.CurrentUser.Id });
            model.CompanyInfo = responseGetInfoById.CompanyInfo;
            ViewBag.DefaultKeyword = _defaultKeyword;

            TempData.Clear();
            TempData.Add("command", command);
            TempData.Add("jobQueryStatus", jobQueryStatus);
            TempData.Add("keyword", keyword);

            return View(model);
        }

        #region Delete
        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("Delete")]
        public ActionResult Delete(Guid id)
        {
            _JobPositionAppService.Delete(new DeleteRequest() { Id = id });
            return List(null);
        }

        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("DeleteSelected")]
        public ActionResult DeleteSelected(JobPositionListViewModel model)
        {
            foreach (var item in model.JobPositionList.Where(x => x.ItemChecked))
            {
                _JobPositionAppService.Delete(new DeleteRequest() { Id = item.Id });
            }
            return List(null);
        }
        #endregion

        #region Post
        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("Post")]
        public ActionResult Post(Guid id)
        {
            var response = _JobPositionAppService.Post(new PostRequest() { Id = id });
            if (response.Exception != null)
            {
                ViewBag.PostError = true;
            }
            return List(null);
        }

        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("PostSelected")]
        public ActionResult PostSelected(JobPositionListViewModel model)
        {
            var response = _CompanyAppService.GetInfoById(new GetInfoByIdRequest() { Id = this.CurrentUserId });
            if (response.CompanyInfo.RemainingQuantity < model.JobPositionList.Where(x => x.ItemChecked).Count())
            {
                ViewBag.PostError = true;
            }
            else 
            {
                foreach (var item in model.JobPositionList.Where(x => x.ItemChecked))
                {
                    _JobPositionAppService.Post(new PostRequest() { Id = item.Id });
                }
            }
            return List(null);
        }
        #endregion

        #region Restore
        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("Restore")]
        public ActionResult Restore(Guid id)
        {
            _JobPositionAppService.Restore(new RestoreRequest() { Id = id });
            return List(null);
        }

        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("RestoreSelected")]
        public ActionResult RestoreSelected(JobPositionListViewModel model)
        {
            foreach (var item in model.JobPositionList.Where(x => x.ItemChecked))
            {
                _JobPositionAppService.Restore(new RestoreRequest() { Id = item.Id });
            }
            return List(null);
        }
        #endregion

        #region Pause
        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("Pause")]
        public ActionResult Pause(Guid id)
        {
            _JobPositionAppService.Pause(new PauseRequest() { Id = id });
            return List(null);
        }

        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("PauseSelected")]
        public ActionResult PauseSelected(JobPositionListViewModel model)
        {
            foreach (var item in model.JobPositionList.Where(x => x.ItemChecked))
            {
                _JobPositionAppService.Pause(new PauseRequest() { Id = item.Id });
            }
            return List(null);
        }
        #endregion

        #region Refresh
        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("Refresh")]
        public ActionResult Refresh(Guid id)
        {
            _JobPositionAppService.Refresh(new RefreshRequest() { Id = id });
            return List(null);
        }

        [HttpPost]
        [ActionName("List")]
        [FormValueRequired("RefreshSelected")]
        public ActionResult RefreshSelected(JobPositionListViewModel model)
        {
            foreach (var item in model.JobPositionList.Where(x => x.ItemChecked))
            {
                _JobPositionAppService.Refresh(new RefreshRequest() { Id = item.Id });
            }
            return List(null);
        }
        #endregion

        #region ChangeSortOrder
        [HttpPost]
        public void ChangeSortOrder(Guid id, int sortOrder)
        {
            _JobPositionAppService.ChangeSortOrder(new ChangeSortOrderRequest() { Id = id, SortOrder = sortOrder });
        }
        #endregion

        #endregion

        #region Add
        public ActionResult Add()
        {
            var model = new JobPositionFormModel()
            {
                UseDepartmentAddress = false,
                IsReceivedEmail = true,
                RecruiteGraduates = false,
                JobType = 105102,//正式
                EducationLevel = 106108,//本科
                Status = (int)JobQueryStatus.New,
                Location = 1283607,//高新区
                DateRage = 30,//默认选中30天
            };
            //为模型附上各种相关信息
            PrepareRelatedDataForJobPositionFormModel(model);
            //用公司信息进行初始化
            model.Fax = model.CompanyInfo.Fax;
            model.Address = model.CompanyInfo.Address;
            model.Tel = model.CompanyInfo.Tel;
            model.Email = model.CompanyInfo.Email;
            model.PostalCode = model.CompanyInfo.PostalCode;
            model.Contact = model.CompanyInfo.Contact;
            return View(model);
        }

        [Authorize]
        [ActionName("Add")]
        [FormValueRequired("SaveInfo")]
        [HttpPost]
        public ActionResult Add(JobPositionFormModel model)
        {
            if (IsValid(model))
            {
                model.StartDate = DateTime.Now.Date;
                model.EndDate = DateTime.Now.AddDays(model.DateRage).Date;
                _JobPositionAppService.CreateJobPosition(
                    new CreateJobPositionRequest()
                    {
                        CompanyId = this.CurrentUserId,
                        JobPositionForm = model
                    }
                );
            }
            PrepareRelatedDataForJobPositionFormModel(model);
            return View(model);
        }

        [Authorize]
        [ActionName("Add")]
        [FormValueRequired("Post")]
        [HttpPost]
        public ActionResult AddPost(JobPositionFormModel model)
        {
            if (IsValid(model))
            {
                model.Status = (int)JobQueryStatus.Active;
                model.StartDate = DateTime.Now.Date;
                model.EndDate = DateTime.Now.AddDays(model.DateRage).Date;
                model.Reposted = DateTime.Now;
                _JobPositionAppService.CreateJobPosition(
                    new CreateJobPositionRequest()
                    {
                        CompanyId = this.CurrentUserId,
                        JobPositionForm = model
                    }
                );
                return RedirectToAction("List");
            }
            PrepareRelatedDataForJobPositionFormModel(model);
            return View(model);
        }

        #endregion

        #region Edit
        public ActionResult Edit(Guid id)
        {
            var response = _JobPositionAppService.GetById(new GetByIdRequest() { Id = id });
            var viewModel = response.ViewModel;
            var model = PrepareJobPositionFormModel(viewModel);
            if (model.Status != (int)JobPositionStatus.Active)
            {
                model.DateRage = new TimeSpan(viewModel.EndDate.Ticks - viewModel.StartDate.Value.Ticks).Days;
            }
            else
            {
                model.EndDateDisplay = viewModel.EndDate.ToString(_dateFormat);
            }
            PrepareRelatedDataForJobPositionFormModel(model);
            return View(model);
        }

        [Authorize]
        [ActionName("Edit")]
        [FormValueRequired("SaveInfo")]
        [HttpPost]
        public ActionResult Edit(JobPositionFormModel model)
        {
            if (IsValid(model))
            {
                if (model.Status != (int)JobPositionStatus.Active)
                {
                    model.StartDate = DateTime.Now.Date;
                    model.EndDate = DateTime.Now.AddDays(model.DateRage).Date;
                }
                _JobPositionAppService.UpdateJobPosition(new UpdateJobPositionRequest() { JobPositionForm = model });
            }
            PrepareRelatedDataForJobPositionFormModel(model);
            return View(model);
        }

        [Authorize]
        [ActionName("Edit")]
        [FormValueRequired("Post")]
        [HttpPost]
        public ActionResult EditPost(JobPositionFormModel model)
        {
            if (IsValid(model))
            {
                model.Status = (int)JobPositionStatus.Active;
                model.StartDate = DateTime.Now.Date;
                model.EndDate = DateTime.Now.AddDays(model.DateRage).Date;
                model.Reposted = DateTime.Now;
                _JobPositionAppService.UpdateJobPosition(new UpdateJobPositionRequest() { JobPositionForm = model });
                return RedirectToAction("List");
            }
            PrepareRelatedDataForJobPositionFormModel(model);
            return View(model);
        }

        #endregion

        #region Other
        private JobPositionFormModel PrepareJobPositionFormModel(JobPositionViewModel entity)
        {
            return new JobPositionFormModel
            {
                Id = entity.Id,
                JobTitle = entity.JobTitle,
                Category = entity.Category,
                JobType = entity.JobType,
                DepartmentId = entity.DepartmentId,
                UseDepartmentAddress = entity.UseDepartmentAddress,
                Wants = entity.Wants,
                Location = entity.Location,
                Responsibilities = entity.Responsibilities,
                Major = entity.Major,
                EducationLevel = entity.EducationLevel,
                YearsOfExperience = entity.YearsOfExperience,
                Language = entity.Language,
                LanguageLevel = entity.LanguageLevel,
                MinAge = entity.MinAge,
                MaxAge = entity.MaxAge,
                Qualifications = entity.Qualifications,
                SalaryRange = entity.SalaryRange,
                MonthlySalary = entity.MonthlySalary,
                IsOpenSalaryRange = entity.IsOpenSalaryRange,
                Welfare = entity.Welfare,
                Contact = entity.Contact,
                Email = entity.Email,
                Tel = entity.Tel,
                Fax = entity.Fax,
                Address = entity.Address,
                PostalCode = entity.PostalCode,
                SortOrder = entity.SortOrder,
                RecruiteGraduates = entity.RecruiteGraduates,
                IsReceivedEmail = entity.IsReceivedEmail,
                Status = entity.Status,
                Gender = entity.Gender
            };
        }

        /// <summary>
        /// 为显示模型附加上相关数据
        /// </summary>
        /// <param name="model"></param>
        private void PrepareRelatedDataForJobPositionFormModel(JobPositionFormModel model)
        {
            model.CategoryList = LovHandler.GetListByParentId(LovHandler.GetLovId(LovType.JobCategory));
            model.SubCategoryList = LovHandler.GetSubListByParentId(LovHandler.GetLovId(LovType.JobCategory));
            model.LocationList = LovHandler.GetListByParentId(LovHandler.GetLovId(LovType.Regionalism));
            model.SubLocationList = LovHandler.GetSubListByParentId(LovHandler.GetLovId(LovType.Regionalism));
            model.JobTypeList = LovHandler.GetListByParentId(LovHandler.GetLovId(LovType.JobType));
            model.EducationLevelList = Common.GenerateDropDownListSource(LovType.EducationLevel);
            model.LanguageLevelList = Common.GenerateDropDownListSource(LovType.Level);
            model.LanguageList = Common.GenerateDropDownListSource(LovType.Language);
            model.SalaryRangeList = Common.GenerateDropDownListSource(LovType.SalaryRange);
            model.YearsOfExperienceList = Common.GenerateDropDownListSource(LovType.YearsOfExperience);
            model.MajorList = Common.GenerateDropDownListSource(LovType.Major);
            //
            // 暂时对应
            var request = new GetAllDepartmentsRequest(CurrentUserId);
            request.PageIndex = 0;
            request.PageCount = 100;

            var response = _DepartmentAppService.GetAllDepartments(request);
            model.DepartmentList = response.PagedDepartments;
            //年龄
            var ageList = new List<SelectListItem>();
            for (var i = 18; i < 60; i++)
            {
                ageList.Add(new SelectListItem() { Text = i.ToString(), Value = i.ToString() });
            }
            model.AgeList = ageList;
            //职位时效范围
            var genderList = LovHandler.GetListByParentId(LovHandler.GetLovId(LovType.Gender)).ToList();
            //移除性别中的"保密"
            genderList.RemoveAt(2);
            model.GenderList = genderList;

            model.DateRageList = new List<SelectListItem>()
            {
                new SelectListItem(){Text = "一个月(30日)", Value="30"  },
                new SelectListItem(){Text = "半个月(15日)", Value="15"  },
                new SelectListItem(){Text = "一周(7日)", Value="7"  },
            };
            //公司信息
            var companyInfoResponse = _CompanyAppService.GetInfoById(new GetInfoByIdRequest() { Id = this.CurrentUserId });
            model.CompanyInfo = companyInfoResponse.CompanyInfo;
        }

        /// <summary>
        /// 判断薪水范围是否有效
        /// </summary>
        /// <param name="model"></param>
        private void CheckMonthlySalary(JobPositionFormModel model)
        {
            var lov = LovHandler.GetById(LovHandler.ConvertLovValueToGuid(model.SalaryRange));
            var salaryValue = lov.Label.Split('-');
            var min = String.IsNullOrWhiteSpace(salaryValue[0]) ? "0" : salaryValue[0];
            var max = String.IsNullOrWhiteSpace(salaryValue[1]) ? int.MaxValue.ToString() : salaryValue[1];
            if (model.MonthlySalary < int.Parse(min) || model.MonthlySalary > int.Parse(max))
            {
                //ModelState.AddModelError("MonthlySalaryRangeError", "月薪范围必须在" + lov.Name);
                ModelState.AddModelError("MonthlySalary", "月薪范围必须在" + lov.Name);
            }
        }

        private bool IsValid(JobPositionFormModel model)
        {
            CheckMonthlySalary(model);
            if (ModelState.IsValid)
            {
                return true;
            }
            else
            {
                //如果没有选择职位
                if (ModelState["Category"].Errors.Any())
                {
                    ViewBag.CategoryError = true;
                }
                //如果没有选择工作地区
                if (ModelState["Location"].Errors.Any())
                {
                    ViewBag.LocationError = true;
                }
            }
            return false;
        }

        #endregion

    }
}
